/*
 * 文件名：WechatSecurity.java
 * 版权：Copyright 2012-2016 广州宝锶信息技术有限公司
 * 创建人：曾毅
 * 创建时间：2017年8月25日 上午11:27:18
 * 修改人：
 * 修改时间：
 * 修改内容：
 */
package com.baothink.weichat.security;

import java.io.UnsupportedEncodingException;

import com.baothink.weichat.conf.WechatConfiguration;
import com.baothink.weichat.dto.common.FeedBackDto;
import com.baothink.weichat.exception.WechatException;
import com.baothink.weichat.nature.AesException;
import com.baothink.weichat.nature.WXBizMsgCrypt;
import com.baothink.weichat.utils.StringUtil;

/**
 * TODO<一句话功能描述><br>
 * TODO<功能详细描述><br>
 * 
 * @author 曾毅
 * @version 1.0,2017年8月25日 上午11:27:18
 * @since weichat 0.0.1
 */
public class WechatSecurity {
	
	private String token="kZgkbJ";
	private String encodingAesKey="EAQXwg3OoAbG3m4q6RhsTrIHo6VJytCjgOJNbAci81D";
	
	public WechatSecurity(){
		
	}
	
	public WechatSecurity(String token,String encodingAesKey){
		this.token=token;
		this.encodingAesKey=encodingAesKey;
	}

	public String verifyURL(FeedBackDto dto) throws AesException, UnsupportedEncodingException{
		WXBizMsgCrypt crypt = getWXBizMsgCrypt();
//		String msgSignature = URLDecoder.decode(dto.getMsg_signature(),"utf-8");
//		String timestamp = URLDecoder.decode(dto.getTimestamp(),"utf-8");
//		String nonce = URLDecoder.decode(dto.getNonce(),"utf-8");
//		String echoStr = URLDecoder.decode(dto.getEchostr(),"utf-8");
		String msgSignature = dto.getMsg_signature();
		String timestamp = dto.getTimestamp();
		String nonce = dto.getNonce();
		String echoStr = dto.getEchostr();
		return crypt.VerifyURL(msgSignature, timestamp, nonce, echoStr);
	}
    
    public String DecryptMsg(String msgSignature,String timeStamp, String nonce, String postData) throws AesException, WechatException{
    	if(StringUtil.isEmptyOrNull(msgSignature)||StringUtil.isEmptyOrNull(timeStamp)||StringUtil.isEmptyOrNull(nonce)){
    		throw new WechatException("验证失败，安全参数为空");
    	}
		WXBizMsgCrypt crypt = getWXBizMsgCrypt();
		return crypt.DecryptMsg(msgSignature, timeStamp, nonce, postData);
	}
	
	public WXBizMsgCrypt getWXBizMsgCrypt() throws AesException{
		return new WXBizMsgCrypt(this.token, this.encodingAesKey, WechatConfiguration.CC.corp_id);
	}
	
	public static void main(String[] args) {
		try {
			WechatSecurity security = new WechatSecurity();
			FeedBackDto dto = new FeedBackDto();
			dto.setMsg_signature("c7871c024a95040395c7b26dfc24406d546209fc");
			dto.setNonce("1805618070");
			dto.setTimestamp("1504057851");
			dto.setEchostr("fgsEbNmvM1u9+4lOwEpgrBh+TijsLvtXdVGBUskEDCW07sqnOpoVXztfubZk32+kFawh6PToPI054FMdnlXD2Q==");
			System.out.println(security.verifyURL(dto));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (AesException e) {
			e.printStackTrace();
		}
	}
}
